import {
  getPage
} from '../../utils/config';
import wxApi from '../../utils/wxApi';
import api from '../../utils/api';
import {
  http,
  $loading,
  $toast
} from '../../utils/utils';
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {

    loading: 1,
    list: [],
    right: [{
      text: '删除',
    }, {
      text: '删除',
      style: 'color: #fa3e3e',
    }],
    // 移动块的id
    moveId: null,
    // 最终停止的位置
    endY: 0,
  },
  /**
   * 跳转店铺
   */
  visitStore(e) {
    const {
      id,
      index,
      shopId,
      open
    } = e.currentTarget.dataset || e.target.dataset;
    if (open) {
      this.toggleSwipe(e, false);
    } else {
      wxApi.navigateTo(getPage.shopcategoryedit, {
        id: id
      });
    }
  },

  /**
   * 开启
   */
  onOpen(e) {
    this.toggleSwipe(e, true);
  },
  fabu() {
    wxApi.navigateTo(getPage.shopcategoryedit);
  },
  toggleSwipe(e, t) {
    const data = e.currentTarget.dataset || e.target.dataset;
    console.log(data);
    const {
      list
    } = this.data;

    if (data.id !== undefined) {
      list[data.index].isOpen = t;
      this.setData({
        list
      });
    }
  },


  /**
   * 删除事件
   */
  handleDelete(e) {
    const that = this;
    const data = e.currentTarget.dataset || e.target.dataset;
    const {
      tabsActive
    } = that.data;
    wx.showModal({
      cancelText: '取消',
      confirmText: '确定',
      content: '是否删除？',
      success(res) {
        if (res.confirm) {
          const list = that.data.list;
          http.post(api.default, {
            data: {
              action: 'delshopcategory',
              shopid: that.data.shopid,
              id: data.id,
            }
          }).then((res) => {
            console.log(res);
            if (res.data.code == 0) {
              list.forEach((item, index) => {
                if (item.ID == data.id) {
                  list.splice(index, 1);
                }
              });
              $toast(`删除成功`, {
                icon: 'success'
              });
              that.setData({
                list: list
              })
              this.init(this.data.list)
            }
            else{
              $toast(res.data.errmsg, {
                icon: 'success'
              });
            }
          })

        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //判断是否登录
    app.getLogin().then((res) => {
      this.setData({
        logged: res.code,
        userId: res.data.user.user_id,
        shopid: res.data.shop.ShopId,
        userRank: res.data.user.user_rank,
      });
      http.post(api.default, {
        data: {
          action: 'getshopcategory',
          shopid: this.data.shopid
        }
      }).then((res) => {
        
        this.setData({
          list: res.data.data
        })
        this.init(this.data.list)
      })
    }).catch((res) => {
      console.log('登录异常--------',res)
      this.setData({
        logged: res
      });
    });
  },

  // 重置列表顺序
  init(dataList) {
    // 列表项高度
    const ITEM_HEIGHT = 40
    // 列表项上外边距
    const ITEM_MARGIN_TOP = 14
    let newDataList = dataList.map((item, index) => {
      item.id = index
      // 重置单项的y坐标(组件默认是绝对定位 left:0  top:0 )
      item.y = (ITEM_HEIGHT + ITEM_MARGIN_TOP) * index + ITEM_MARGIN_TOP
      return item
    })
    let listStr = this.data.list.map(m=>m.ID).toString()
    let newlistStr = newDataList.map(m=>m.ID).toString()

    console.log('listtttttt=',newDataList)
    this.setData({
      list: newDataList
    })
    if(listStr !== newlistStr){
      let sortList = newDataList.map((m,i)=>{
        return{
          ID:m.ID,
          Orders:i
        }
      })
      http.post(api.default, {
        data: {
          action: 'updateshopcategoryorders',
          req: JSON.stringify(sortList)
        }
      }).then(res=>{})
    }
  },

  // 移动中-获取移动元素的id,实时获取移动元素的y坐标
  moving(e) {
    this.setData({
      moveId: e.currentTarget.dataset.moveid,
      endY: e.detail.y,
    })
  },
  // 移动后
  moved() {
    let {
      list,
      moveId,
      endY
    } = this.data
    let newDataList = JSON.parse(JSON.stringify(list))
    console.log('moveId\endY====',moveId,endY)
    console.log('newDataList====',newDataList)
    newDataList[moveId].y = endY
    newDataList = newDataList.sort((a, b) => a.y - b.y)
    this.init(newDataList)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})